<?php

namespace app\api\controller;

use app\model\AdminModel;
use Qiniu\Auth;

// 引入上传类
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\Exception;


class Upload
{

    private $accessKey;
    private $secretKey ;
    private $bucket;
    private $domin;
    private $dir;

    public function __construct()
    {

        $qiniu_confifg = config("qiniu");
        $this->accessKey = $qiniu_confifg['accessKey'];
        $this->secretKey = $qiniu_confifg['secretKey'];
        $this->bucket = $qiniu_confifg['bucket'];
        $this->domin = $qiniu_confifg['domin'];
        $this->dir = $qiniu_confifg['dir'];
    }


    public function getToken(){
        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);

        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);

        return json(['code' => 1, 'msg' => "success",'data'=>$token]);
    }


    /*
   * 七牛云上传文件
   *
   * */


    public function delQiNiuFile()
    {

        $token = !empty($header) && isset($header["token"]) ? $header["token"] : "";

        if(!isset($token) || empty($token)){
            return json(['code' => -2, 'msg' => '请先登录']);
        }
        $model = new AdminModel();
        $user = $model->getCache($token);
        if(!$user){
            return json(['code' => -2, 'msg' => '登录已过期']);
        }

        $oldFiles = request()->param("oldFiles");

        if(empty($oldFiles)){
            return json(['code' => 0, 'msg' => "请选择要删除的图片"]);
        }


        try {
            $fail  = [];
            foreach ($oldFiles as $oldFile){
                $delFile = $this->delFile($oldFile);
                if(!$delFile){
                    $fail[] = $oldFile;
                }
            }


            if(count($fail) <= 0){
                return json(['code' => 1, 'msg' => "删除成功"]);
            }else{
                return json(['code' => 0, 'msg' => count($fail)."删除失败",'data'=>$fail]);
            }

        }catch (\Exception $e){
            return  json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }



    /*
     * 七牛云上传文件
     *
     * */


    public function qiniu()
    {

        $oldFile = request()->param("oldFile");

        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);

        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);


        $allow_exts = array('jpg', 'jpeg', 'gif', 'png', 'txt');

        $max_size = 5 * 1024 * 1024;

        if ($_FILES['file']['error'] != UPLOAD_ERR_OK) {
            return json(['code' => 0, 'msg' => "上传失败，请稍后再试"]);
        }

        $temp_file = $_FILES['file']['tmp_name'];

        $file_name = $_FILES['file']['name'];

        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));


        if (!in_array($file_ext, $allow_exts)) {
            return json(['code' => 0, 'msg' => "上传失败，请稍后再试"]);
        }

        if ($_FILES['file']['size'] > $max_size) {
            return json(['code' => 0, 'msg' => "文件太大了，请选择手动上传"]);
        }


        if (!is_uploaded_file($temp_file)) {
            return json(['code' => 0, 'msg' => "非法上传，请重新上传"]);
        }

        // 要上传文件的本地路径
        $filePath = $_FILES['file']['tmp_name'];

        // 上传到七牛存储后保存的文件名
        $key = $this->dir .'/'.md5($file_name.time()).'.'.$file_ext;

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传，该方法会判断文件大小，进而决定使用表单上传还是分片上传，无需手动配置。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        if ($err !== null) {

            addLog("qiniu_err.log",['file'=>$_FILES, 'err'=>$err]);

            return json(['code' => 0, 'msg' => "上传失败：".json_encode($err,256)]);
        } else {


            // ✅ 上传成功，现在处理删除 oldFile
            if (!empty($oldFile)) {
                $this->delFile($oldFile);
            }


            return json(['code' => 1, 'msg' => "上传成功",'data'=>$this->domin.'/'.$key]);
        }

    }



    /*
   * 七牛云上传文件
   *
   * */


    public function qiniuFWB()
    {


        $oldFile = request()->param("oldFile");

        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);

        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);


        $allow_exts = array('jpg', 'jpeg', 'gif', 'png', 'txt');

        $max_size = 5*1024 * 1024;

        if ($_FILES['file']['error'] != UPLOAD_ERR_OK) {
            return json(['code' => -1, 'msg' => "上传失败，请稍后再试"]);
        }

        $temp_file = $_FILES['file']['tmp_name'];

        $file_name = $_FILES['file']['name'];

        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));


        if (!in_array($file_ext, $allow_exts)) {
            return json(['code' => -1, 'msg' => "上传失败，请稍后再试"]);
        }

        if ($_FILES['file']['size'] > $max_size) {
            return json(['code' => -1, 'msg' => "文件大小不能超过5MB，请重新上传"]);
        }


        if (!is_uploaded_file($temp_file)) {
            return json(['code' => -1, 'msg' => "非法上传，请重新上传"]);
        }

        // 要上传文件的本地路径
        $filePath = $_FILES['file']['tmp_name'];

        // 上传到七牛存储后保存的文件名
        $key = $this->dir .'/'.md5($file_name.time()).'.'.$file_ext;

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传，该方法会判断文件大小，进而决定使用表单上传还是分片上传，无需手动配置。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        $data['location'] = $this->domin.'/'.$key;

        if ($err !== null) {

            addLog("qiniu_err.log",['file'=>$_FILES, 'err'=>$err]);

            return json(['code' => -1, 'msg' => "上传失败"]);
        } else {


            // ✅ 上传成功，现在处理删除 oldFile
            if (!empty($oldFile)) {
                $this->delFile($oldFile);
            }

            $data['location'] = $this->domin.'/'.$key;

            return  json($data);
        }

    }


    /*
     * 删除图片
     * */
    private function delFile($oldFile){

        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);

        // 假设 $oldFile 是完整的 URL，如：http://example.com/upload/abc.jpg
        $keyToDelete = $this->extractQiniuKey($oldFile);

        if (!$keyToDelete) {
           throw new Exception("文件路径解析错误");
        }
        $bucketMgr = new BucketManager($auth);

        list($deleteErr) = $bucketMgr->delete($this->bucket, $keyToDelete);

        if ($deleteErr) {
            // 可选：记录删除失败日志，但不返回错误（避免影响上传成功）
            addLog("qiniu_delete_err.log", [
                'oldFile' => $oldFile,
                'key' => $keyToDelete,
                'error' => $deleteErr
            ]);
            // 不中断流程
            throw new Exception($deleteErr);
        }

        return true;
    }

    /**
     * 从 URL 中提取七牛存储的 key（路径）
     * @param string $url 文件 URL
     * @return string|null 提取的 key 或 null
     */
    private function extractQiniuKey($url)
    {
        if (empty($url)) return null;

        // 去掉协议和域名，只保留路径
        $path = parse_url($url, PHP_URL_PATH); // 例如：/upload/abc.jpg

        if (!$path) return null;

        // 去掉前面的斜杠
        $key = ltrim($path, '/');

        // 可选：验证 key 是否在你的目录下（如 $this->dir）
        // if (strpos($key, $this->dir . '/') !== 0) {
        //     return null; // 不是你的目录，防止误删
        // }

        return $key;
    }


}
